<script setup lang="ts">
import Turnstile, { cfRules } from '~comp/Turnstile.vue';

const props = defineProps<{ onToSignIn?: () => void; onFulfilled?: () => void }>();

const form = useAntdForm({
  email: {
    value: '',
    rules: [{ required: true, type: 'email', message: $t('aw95tLwTkGmrgSVCHW') }],
  },
  from_type: {
    value: 1,
  },
  cf_turnstile_response: {
    value: '',
    rules: cfRules,
  },
});

const turnstileDomRef = ref();

const forgetMut = useMutation({
  mutationKey: [apis.apiAuthForgetPassword.id],
  mutationFn: apis.apiAuthForgetPassword.setDefaultConfig({ successMessage: true }),
  onSuccess(e, { requestBody: body }) {
    props.onFulfilled?.();
    body?.email && globalPopups.resetPassword.open({ email: body.email });
  },
  onError() {
    turnstileDomRef.value?.reset?.();
    form.$form?.clearValidate?.();
  },
});

const getIsLoadingRef = computed(() => forgetMut.isPending.value);

function confirm() {
  forgetMut.mutate({ requestBody: form.state });
}
</script>

<template>
  <div>
    <AForm v-bind="form.props" class="ant-cover__Form-compact" :disabled="getIsLoadingRef" @finish="confirm()">
      <TAntdTheme component="Input" theme="light">
        <AFormItem v-bind="form.itemProps.email">
          <AInput v-model:value="form.state.email" :placeholder="$t('hVaEobWzd70kjGP9Awnt')">
            <template #prefix>
              <i class="i-ri:mail-fill mr-1 text-1.2em text-sys-text-body" />
            </template>
          </AInput>
        </AFormItem>
        <AFormItem v-bind="form.itemProps.cf_turnstile_response">
          <Turnstile ref="turnstileDomRef" v-model:value="form.state.cf_turnstile_response" />
        </AFormItem>
      </TAntdTheme>

      <div class="mt-3 text-sys-text-body">
        {{ $t('hryrhZe7755O7Kh6Ym7Yu') }}
      </div>

      <AButton
        class="ant-cover__Button-3d-primary mt-4 w-full"
        type="primary"
        htmlType="submit"
        :loading="getIsLoadingRef"
        :disabled="getIsLoadingRef"
      >
        {{ $t('jkGMvmfX9akyN4gOox2') }}
      </AButton>
    </AForm>

    <div class="my-2 text-center">
      {{ $t('iUd6Zdwwr45CQpJsCatS') }} <span class="cursor-pointer url-yellow-underline" @click="props.onToSignIn">{{ $t('qwZi820O3qWpsae62Juc') }}</span>
    </div>
  </div>
</template>
